#include "frmdeviceupdate.h"
#include "ui_frmdeviceupdate.h"
#include <QMessageBox>
#include <QThread>
#include <QTextEdit>
#include <QTcpSocket>
#include <QSerialPort>
#include <QDateTime>
#include <QStyledItemDelegate>
#include <QPainter>
#include <QEvent>
#include <QMouseEvent>
#include <QStyleOptionViewItem>
#include <QModelIndex>
#include <QDebug>
#include <QWidget>

class CenteredItemDelegate : public QStyledItemDelegate {
public:
    using QStyledItemDelegate::QStyledItemDelegate;

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
        QStyleOptionViewItem centeredOption = option;
        centeredOption.displayAlignment = Qt::AlignCenter;
        QStyledItemDelegate::paint(painter, centeredOption, index);
    }
};

frmdeviceupdate::frmdeviceupdate(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::frmdeviceupdate),
    mainWindow(qobject_cast<frmmain*>(parent)),
    isCommandMode(false),
    isWaitingForMqttConfig(false),
    lastCommand(""),
    isWaitingForResponse(false),
    isProcessingTopicQuery(false),
    isWaitingForTopicResponse(false),
    waitSeconds(0)
{
    ui->setupUi(this);

    if (!mainWindow) {
        updateMainResponse("错误：无法获取主窗口指针");
    } else {
        qDebug() << "frmdeviceupdate: 主窗口指针获取成功";
    }

    ui->exitCommandModeButton->setEnabled(false);
    enableConfigControls(false);
    updateSettingModeButtonState();

    responseTimer.setSingleShot(true);
    connect(&responseTimer, &QTimer::timeout, this, &frmdeviceupdate::onResponseTimeout);

    if (mainWindow) {
        connect(mainWindow, &frmmain::serialConnectionChanged, this, &frmdeviceupdate::onSerialConnectionChanged);
        connect(mainWindow, &frmmain::tcpConnectionChanged, this, &frmdeviceupdate::onTcpConnectionChanged);
        connect(mainWindow, &frmmain::serialDataReceived, this, &frmdeviceupdate::onSerialDataReceived);
        connect(mainWindow, &frmmain::tcpDataReceived, this, &frmdeviceupdate::onTcpDataReceived);
        qDebug() << "frmdeviceupdate: 已连接 frmmain 的信号";
    } else {
        qDebug() << "frmdeviceupdate: 无法连接 frmmain 的信号";
    }

    connect(ui->queryTopicTypeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &frmdeviceupdate::on_queryTopicTypeComboBox_currentIndexChanged);

    ui->queryTopicTypeComboBox->setEditable(true);
    QLineEdit *lineEdit = ui->queryTopicTypeComboBox->lineEdit();
    if (lineEdit) {
        lineEdit->setAlignment(Qt::AlignCenter);
        lineEdit->setReadOnly(true);
        lineEdit->installEventFilter(this);
    }

    CenteredItemDelegate *delegate = new CenteredItemDelegate(ui->queryTopicTypeComboBox);
    ui->queryTopicTypeComboBox->setItemDelegate(delegate);
    ui->queryTopicTypeComboBox->installEventFilter(this);

    connect(&waitLogTimer, &QTimer::timeout, this, &frmdeviceupdate::onWaitLogTimeout);
}

frmdeviceupdate::~frmdeviceupdate()
{
    delete ui;
}

void frmdeviceupdate::on_enterCommandModeButton_clicked()
{
    if (!mainWindow) {
        updateMainResponse("错误：主窗口指针无效");
        return;
    }

    if (!mainWindow->getIsTcpConnected() && !mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立 TCP 或串口连接");
        return;
    }

    sendCommandModeCommand(true);
    isCommandMode = true;
    ui->enterCommandModeButton->setEnabled(false);
    ui->exitCommandModeButton->setEnabled(true);
    enableConfigControls(true);
    updateMainResponse("已进入指令模式 ($CFG+)");
}

void frmdeviceupdate::on_exitCommandModeButton_clicked()
{
    if (!mainWindow) {
        updateMainResponse("错误：主窗口指针无效");
        return;
    }

    if (!mainWindow->getIsTcpConnected() && !mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立 TCP 或串口连接");
        return;
    }

    sendCommandModeCommand(false);
    isCommandMode = false;
    ui->enterCommandModeButton->setEnabled(true);
    ui->exitCommandModeButton->setEnabled(false);
    enableConfigControls(false);
    resetConfigFields();
    updateMainResponse("已退出指令模式 ($CFG-)");
}

void frmdeviceupdate::on_sendConfigButton_clicked()
{
    if (!mainWindow) {
        updateMainResponse("错误：主窗口指针无效");
        return;
    }

    if (!mainWindow->getIsTcpConnected() && !mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立 TCP 或串口连接");
        return;
    }

    if (!isCommandMode) {
        updateMainResponse("错误：请先进入指令模式");
        return;
    }

    QString mqttIp = ui->mqttIpLineEdit->text().trimmed();
    QString mqttPort = ui->mqttPortLineEdit->text().trimmed();
    QString mqttDeviceId = ui->mqttDeviceIdLineEdit->text().trimmed();
    QString mqttUsername = ui->mqttUsernameLineEdit->text().trimmed();
    QString mqttPassword = ui->mqttPasswordLineEdit->text().trimmed();

    if (mqttIp.isEmpty() || mqttPort.isEmpty() || mqttDeviceId.isEmpty()) {
        updateMainResponse("错误：MQTT IP、端口和设备 ID 不能为空");
        return;
    }

    bool ok;
    int port = mqttPort.toInt(&ok);
    if (!ok || port < 1 || port > 65535) {
        updateMainResponse("错误：MQTT 端口号必须是 1-65535 之间的整数");
        return;
    }

    QString command = QString("$MQTT,%1,%2,%3,%4,%5\r\n")
                         .arg(mqttIp)
                         .arg(mqttPort)
                         .arg(mqttDeviceId)
                         .arg(mqttUsername)
                         .arg(mqttPassword);
    updateMainResponse("准备下发 MQTT 配置...");

    bool useTcp = mainWindow->getIsTcpConnected();
    if (useTcp) {
        QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
        if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
            lastCommand = command.trimmed();
            tcpSocket->write(command.toUtf8());
            tcpSocket->flush();
            updateMainResponse("发送: " + command.trimmed());
            QThread::msleep(100);
            updateMainResponse("MQTT 配置已通过网络发送，等待设备回复...");
        } else {
            updateMainResponse("错误：TCP 连接无效");
            return;
        }
    } else {
        QSerialPort *serialPort = mainWindow->getSerialPort();
        if (serialPort->isOpen()) {
            lastCommand = command.trimmed();
            serialPort->write(command.toUtf8());
            serialPort->flush();
            updateMainResponse("发送: " + command.trimmed());
            QThread::msleep(100);
            updateMainResponse("MQTT 配置已通过串口发送，等待设备回复...");
        } else {
            updateMainResponse("错误：串口连接无效");
            return;
        }
    }

    waitSeconds = 0;
    waitLogTimer.start(1000);
    sendCommandModeCommand(false);
    isCommandMode = false;
    ui->enterCommandModeButton->setEnabled(true);
    ui->exitCommandModeButton->setEnabled(false);
    enableConfigControls(false);
}

void frmdeviceupdate::on_cancelButton_clicked()
{
    if (isCommandMode) {
        if (mainWindow && (mainWindow->getIsTcpConnected() || mainWindow->getIsSerialConnected())) {
            sendCommandModeCommand(false);
        }
        isCommandMode = false;
        ui->enterCommandModeButton->setEnabled(true);
        ui->exitCommandModeButton->setEnabled(false);
    }

    resetConfigFields();
    enableConfigControls(false);
    updateMainResponse("已取消操作，配置已重置");
}

void frmdeviceupdate::on_saveConfigButton_clicked()
{
    if (!mainWindow) {
        updateMainResponse("错误：主窗口指针无效");
        return;
    }

    if (!mainWindow->getIsTcpConnected() && !mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立 TCP 或串口连接");
        return;
    }

    if (!isCommandMode) {
        updateMainResponse("错误：请先进入指令模式");
        return;
    }

    QString command = "$SAVE\r\n";
    lastCommand = command.trimmed();
    isWaitingForResponse = true;
    updateMainResponse("发送保存配置命令: " + command.trimmed());

    bool useTcp = mainWindow->getIsTcpConnected();
    if (useTcp) {
        QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
        if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
            tcpSocket->write(command.toUtf8());
            tcpSocket->flush();
        } else {
            updateMainResponse("错误：TCP 连接无效");
            isWaitingForResponse = false;
            return;
        }
    } else {
        QSerialPort *serialPort = mainWindow->getSerialPort();
        if (serialPort->isOpen()) {
            serialPort->write(command.toUtf8());
            serialPort->flush();
        } else {
            updateMainResponse("错误：串口连接无效");
            isWaitingForResponse = false;
            return;
        }
    }

    waitSeconds = 0;
    waitLogTimer.start(1000);
    startResponseTimer();
}

void frmdeviceupdate::on_loadConfigButton_clicked()
{
    if (!mainWindow) {
        updateMainResponse("错误：主窗口指针无效");
        return;
    }

    if (!mainWindow->getIsTcpConnected() && !mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立 TCP 或串口连接");
        return;
    }

    if (!isCommandMode) {
        updateMainResponse("错误：请先进入指令模式");
        return;
    }

    resetConfigFields();
    sendMqttQueryCommand();
    isWaitingForMqttConfig = true;
    updateMainResponse("已发送 MQTT 配置查询指令 ($MQTTS,?)，等待设备回复...");
    waitSeconds = 0;
    waitLogTimer.start(1000);
    startResponseTimer();
}

void frmdeviceupdate::onSerialConnectionChanged(bool connected)
{
    updateSettingModeButtonState();
}

void frmdeviceupdate::onTcpConnectionChanged(bool connected)
{
    updateSettingModeButtonState();
}

void frmdeviceupdate::updateSettingModeButtonState()
{
    bool isConnected = mainWindow && (mainWindow->getIsSerialConnected() || mainWindow->getIsTcpConnected());
    ui->enterCommandModeButton->setEnabled(isConnected && !isCommandMode);
    ui->exitCommandModeButton->setEnabled(isConnected && isCommandMode);
}

void frmdeviceupdate::sendCommandModeCommand(bool enter)
{
    if (!mainWindow) return;

    QString command = enter ? "$CFG+\r\n" : "$CFG-\r\n";
    if (mainWindow->getIsSerialConnected()) {
        QSerialPort *serialPort = mainWindow->getSerialPort();
        if (serialPort->isOpen()) {
            lastCommand = command.trimmed();
            serialPort->write(command.toUtf8());
            serialPort->flush();
        }
    }
    if (mainWindow->getIsTcpConnected()) {
        QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
        if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
            lastCommand = command.trimmed();
            tcpSocket->write(command.toUtf8());
            tcpSocket->flush();
        }
    }
}

void frmdeviceupdate::updateMainResponse(const QString &msg)
{
    if (mainWindow) {
        QTextEdit *responseTextEdit = mainWindow->findChild<QTextEdit*>("responseTextEdit");
        if (responseTextEdit) {
            responseTextEdit->append(msg);
            responseTextEdit->repaint();
        } else {
            qDebug() << "错误：无法找到 responseTextEdit 控件";
        }
    }
}

void frmdeviceupdate::enableConfigControls(bool enable)
{
    ui->mqttIpLineEdit->setEnabled(enable);
    ui->mqttPortLineEdit->setEnabled(enable);
    ui->mqttDeviceIdLineEdit->setEnabled(enable);
    ui->mqttUsernameLineEdit->setEnabled(enable);
    ui->mqttPasswordLineEdit->setEnabled(enable);
    ui->mqttTopicLineEdit->setEnabled(enable);
    ui->sendConfigButton->setEnabled(enable);
    ui->cancelButton->setEnabled(enable);
    ui->queryTopicTypeComboBox->setEnabled(enable);
    ui->btnReportTopic->setEnabled(enable);
    ui->btnDownlinkTopic->setEnabled(enable);
    ui->btnResponseTopic->setEnabled(enable);
}

void frmdeviceupdate::resetConfigFields()
{
    ui->mqttIpLineEdit->clear();
    ui->mqttPortLineEdit->clear();
    ui->mqttDeviceIdLineEdit->clear();
    ui->mqttUsernameLineEdit->clear();
    ui->mqttPasswordLineEdit->clear();
    ui->mqttTopicLineEdit->clear();
}

void frmdeviceupdate::sendMqttQueryCommand()
{
    QString command = "$MQTTS,?\r\n";
    lastCommand = command.trimmed();
    bool useTcp = mainWindow->getIsTcpConnected();
    if (useTcp) {
        QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
        if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
            tcpSocket->write(command.toUtf8());
            tcpSocket->flush();
            updateMainResponse("发送: " + command.trimmed());
        } else {
            updateMainResponse("错误：TCP 连接无效");
            isWaitingForMqttConfig = false;
        }
    } else {
        QSerialPort *serialPort = mainWindow->getSerialPort();
        if (serialPort->isOpen()) {
            serialPort->write(command.toUtf8());
            serialPort->flush();
            updateMainResponse("发送: " + command.trimmed());
        } else {
            updateMainResponse("错误：串口连接无效");
            isWaitingForMqttConfig = false;
        }
    }
    waitSeconds = 0;
    waitLogTimer.start(1000);
}

void frmdeviceupdate::onSerialDataReceived(const QString &data)
{
    qDebug() << "frmdeviceupdate: 收到串口数据: " << data;
    if (isWaitingForMqttConfig) {
        qDebug() << "frmdeviceupdate: 开始处理 MQTT 配置响应";
        QMetaObject::invokeMethod(this, [this, data]() {
            parseMqttConfigResponse(data);
        }, Qt::QueuedConnection);
    }
    if (isWaitingForTopicResponse) {
        qDebug() << "frmdeviceupdate: 开始处理 Topic 响应";
        QMetaObject::invokeMethod(this, [this, data]() {
            parseTopicResponse(data);
        }, Qt::QueuedConnection);
    }
    if (isWaitingForResponse) {
        qDebug() << "frmdeviceupdate: 开始处理保存配置响应";
        QMetaObject::invokeMethod(this, [this, data]() {
            parseSaveConfigResponse(data);
        }, Qt::QueuedConnection);
    }
}

void frmdeviceupdate::onTcpDataReceived(const QString &data)
{
    qDebug() << "frmdeviceupdate: 收到 TCP 数据: " << data;
    if (isWaitingForMqttConfig) {
        qDebug() << "frmdeviceupdate: 开始处理 MQTT 配置响应";
        QMetaObject::invokeMethod(this, [this, data]() {
            parseMqttConfigResponse(data);
        }, Qt::QueuedConnection);
    }
    if (isWaitingForTopicResponse) {
        qDebug() << "frmdeviceupdate: 开始处理 Topic 响应";
        QMetaObject::invokeMethod(this, [this, data]() {
            parseTopicResponse(data);
        }, Qt::QueuedConnection);
    }
    if (isWaitingForResponse) {
        qDebug() << "frmdeviceupdate: 开始处理保存配置响应";
        QMetaObject::invokeMethod(this, [this, data]() {
            parseSaveConfigResponse(data);
        }, Qt::QueuedConnection);
    }
}

void frmdeviceupdate::parseMqttConfigResponse(const QString &data)
{
    if (!isWaitingForMqttConfig) {
        return;
    }

    if (!data.startsWith("$MQTTS,")) {
        return;
    }

    QStringList parts = data.trimmed().split(",");
    if (parts.size() == 6) {
        updateMainResponse("警告：设备返回的 MQTT 配置格式不匹配，期望字段为 IP、端口、设备ID、用户名、密码、Topic，仅收到 IP 和端口将被更新");

        QString ip = parts[1].trimmed();
        QString port = parts[2].trimmed();

        if (ip.isEmpty()) {
            updateMainResponse("错误：设备返回的 MQTT IP 为空");
            isWaitingForMqttConfig = false;
            responseTimer.stop();
            return;
        }

        bool ok;
        int portNum = port.toInt(&ok);
        if (!ok || portNum < 1 || portNum > 65535) {
            updateMainResponse("错误：设备返回的 MQTT 端口号无效（必须为 1-65535 之间的整数）");
            isWaitingForMqttConfig = false;
            responseTimer.stop();
            return;
        }

        if (!ui->mqttIpLineEdit || !ui->mqttPortLineEdit || !ui->mqttDeviceIdLineEdit ||
            !ui->mqttUsernameLineEdit || !ui->mqttPasswordLineEdit || !ui->mqttTopicLineEdit) {
            updateMainResponse("错误：MQTT 配置页面控件未正确初始化");
            isWaitingForMqttConfig = false;
            responseTimer.stop();
            return;
        }

        ui->mqttIpLineEdit->setText(ip);
        ui->mqttPortLineEdit->setText(port);
        ui->mqttDeviceIdLineEdit->clear();
        ui->mqttUsernameLineEdit->clear();
        ui->mqttPasswordLineEdit->clear();
        ui->mqttTopicLineEdit->clear();

        updateMainResponse("部分 MQTT 配置已从设备读取并更新到界面: IP = " + ip + ", 端口 = " + port);
        isWaitingForMqttConfig = false;
        responseTimer.stop();
        return;
    }
    else if (parts.size() != 7) {
        updateMainResponse("错误：设备返回的 MQTT 配置格式无效，期望 7 个字段（IP、端口、设备ID、用户名、密码、Topic），实际为 " + QString::number(parts.size()) + " 个字段");
        isWaitingForMqttConfig = false;
        responseTimer.stop();
        return;
    }

    QString ip = parts[1].trimmed();
    QString port = parts[2].trimmed();
    QString deviceId = parts[3].trimmed();
    QString username = parts[4].trimmed();
    QString password = parts[5].trimmed();
    QString topic = parts[6].trimmed();

    if (ip.isEmpty()) {
        updateMainResponse("错误：设备返回的 MQTT IP 为空");
        isWaitingForMqttConfig = false;
        responseTimer.stop();
        return;
    }

    bool ok;
    int portNum = port.toInt(&ok);
    if (!ok || portNum < 1 || portNum > 65535) {
        updateMainResponse("错误：设备返回的 MQTT 端口号无效（必须为 1-65535 之间的整数）");
        isWaitingForMqttConfig = false;
        responseTimer.stop();
        return;
    }

    if (deviceId.isEmpty()) {
        updateMainResponse("错误：设备返回的设备 ID 为空");
        isWaitingForMqttConfig = false;
        responseTimer.stop();
        return;
    }

    if (!ui->mqttIpLineEdit || !ui->mqttPortLineEdit || !ui->mqttDeviceIdLineEdit ||
        !ui->mqttUsernameLineEdit || !ui->mqttPasswordLineEdit || !ui->mqttTopicLineEdit) {
        updateMainResponse("错误：MQTT 配置页面控件未正确初始化");
        isWaitingForMqttConfig = false;
        responseTimer.stop();
        return;
    }

    ui->mqttIpLineEdit->setText(ip);
    ui->mqttPortLineEdit->setText(port);
    ui->mqttDeviceIdLineEdit->setText(deviceId);
    ui->mqttUsernameLineEdit->setText(username);
    ui->mqttPasswordLineEdit->setText(password);
    ui->mqttTopicLineEdit->setText(topic);

    updateMainResponse("MQTT 配置已从设备读取并更新到界面: IP = " + ip + ", 端口 = " + port +
                      ", 设备 ID = " + deviceId + ", 用户名 = " + username +
                      ", 密码 = " + password + ", Topic = " + topic);
    isWaitingForMqttConfig = false;
    responseTimer.stop();
}

void frmdeviceupdate::parseTopicResponse(const QString &data)
{
    if (!isWaitingForTopicResponse) {
        return;
    }

    if (!data.startsWith("$TOPC,")) {
        return;
    }

    QStringList parts = data.trimmed().split(",");
    if (parts.size() != 3) {
        updateMainResponse("错误：设备返回的 Topic 格式无效，期望 3 个字段，实际为 " + QString::number(parts.size()) + " 个字段");
        isWaitingForTopicResponse = false;
        isProcessingTopicQuery = false;
        responseTimer.stop();
        return;
    }

    QString type = parts[1].trimmed();
    QString topic = parts[2].trimmed();

    QString desc;
    if (lastCommand == "$TOPC,?,1") {
        desc = "上报topic";
    } else if (lastCommand == "$TOPC,?,2") {
        desc = "下行topic";
    } else if (lastCommand == "$TOPC,?,3") {
        desc = "响应topic";
    } else {
        desc = "未知topic";
    }

    updateMainResponse("设备返回 " + desc + ": " + topic);
    ui->mqttTopicLineEdit->setText(topic);

    isWaitingForTopicResponse = false;
    isProcessingTopicQuery = false;
    responseTimer.stop();
    waitLogTimer.stop();
    waitSeconds = 0;
}

void frmdeviceupdate::parseSaveConfigResponse(const QString &data)
{
    if (!isWaitingForResponse) {
        return;
    }

    if (data == "$SAVEOK") {
        updateMainResponse("设备回复：配置保存成功");
        isWaitingForResponse = false;
        responseTimer.stop();
        return;
    } else if (data == "$SAVEERR") {
        updateMainResponse("设备回复：配置保存失败");
        isWaitingForResponse = false;
        responseTimer.stop();
        QMessageBox::warning(this, "保存失败", "设备无法保存配置，请检查设备状态或重试");
        return;
    }

    updateMainResponse("未知回复: " + data);
}

void frmdeviceupdate::onResponseTimeout()
{
    if (isWaitingForMqttConfig) {
        updateMainResponse("错误：设备未响应，查询超时");
        isWaitingForMqttConfig = false;
    }
    if (isWaitingForResponse) {
        updateMainResponse("错误：设备未响应，保存配置超时");
        isWaitingForResponse = false;
    }
    if (isWaitingForTopicResponse) {
        updateMainResponse("错误：设备未响应，Topic 查询超时");
        isWaitingForTopicResponse = false;
        isProcessingTopicQuery = false;
    }
}

void frmdeviceupdate::startResponseTimer()
{
    responseTimer.start(15000);
}

void frmdeviceupdate::on_btnReportTopic_clicked()
{
    QString topic = ui->mqttTopicLineEdit->text().trimmed();
    if (topic.isEmpty()) {
        updateMainResponse("错误：topic 不能为空");
        return;
    }
    QString command = QString("$TOPC,1,%1\r\n").arg(topic);
    sendTopicCommand(command, "上报topic");
    updateMainResponse("发送: " + command.trimmed());
    sendCommandModeCommand(false);
    isCommandMode = false;
    ui->enterCommandModeButton->setEnabled(true);
    ui->exitCommandModeButton->setEnabled(false);
    enableConfigControls(false);
}

void frmdeviceupdate::on_btnDownlinkTopic_clicked()
{
    QString topic = ui->mqttTopicLineEdit->text().trimmed();
    if (topic.isEmpty()) {
        updateMainResponse("错误：topic 不能为空");
        return;
    }
    QString command = QString("$TOPC,2,%1\r\n").arg(topic);
    sendTopicCommand(command, "下行topic");
    updateMainResponse("发送: " + command.trimmed());
    sendCommandModeCommand(false);
    isCommandMode = false;
    ui->enterCommandModeButton->setEnabled(true);
    ui->exitCommandModeButton->setEnabled(false);
    enableConfigControls(false);
}

void frmdeviceupdate::on_btnResponseTopic_clicked()
{
    QString topic = ui->mqttTopicLineEdit->text().trimmed();
    if (topic.isEmpty()) {
        updateMainResponse("错误：topic 不能为空");
        return;
    }
    QString command = QString("$TOPC,3,%1\r\n").arg(topic);
    sendTopicCommand(command, "响应topic");
    updateMainResponse("发送: " + command.trimmed());
    sendCommandModeCommand(false);
    isCommandMode = false;
    ui->enterCommandModeButton->setEnabled(true);
    ui->exitCommandModeButton->setEnabled(false);
    enableConfigControls(false);
}

void frmdeviceupdate::on_queryTopicTypeComboBox_currentIndexChanged(int index)
{
    if (!ui->queryTopicTypeComboBox->isEnabled()) return;
    if (index == 0) return;

    if (isProcessingTopicQuery || isWaitingForTopicResponse) {
        qDebug() << "on_queryTopicTypeComboBox_currentIndexChanged: 正在处理查询或等待响应，忽略重复信号, index=" << index;
        return;
    }

    isProcessingTopicQuery = true;
    isWaitingForTopicResponse = true;

    QString command;
    QString desc;
    switch (index) {
    case 1:
        command = "$TOPC,?,1\r\n";
        desc = "查询上报topic";
        break;
    case 2:
        command = "$TOPC,?,2\r\n";
        desc = "查询下行topic";
        break;
    case 3:
        command = "$TOPC,?,3\r\n";
        desc = "查询响应topic";
        break;
    default:
        isProcessingTopicQuery = false;
        isWaitingForTopicResponse = false;
        return;
    }

    lastCommand = command.trimmed();
    sendTopicCommand(command, desc);
    qDebug() << "on_queryTopicTypeComboBox_currentIndexChanged called, index=" << index;
    waitSeconds = 0;
    waitLogTimer.start(1000);
    startResponseTimer();
}

void frmdeviceupdate::sendTopicCommand(const QString &command, const QString &desc)
{
    if (!mainWindow) {
        updateMainResponse("错误：主窗口指针无效");
        isProcessingTopicQuery = false;
        isWaitingForTopicResponse = false;
        return;
    }

    bool useTcp = mainWindow->getIsTcpConnected();
    if (useTcp) {
        QTcpSocket *tcpSocket = mainWindow->getTcpSocket();
        if (tcpSocket->state() == QAbstractSocket::ConnectedState) {
            tcpSocket->write(command.toUtf8());
            tcpSocket->flush();
            updateMainResponse(desc + "命令已通过TCP发送: " + command.trimmed());
            qDebug() << "sendTopicCommand: TCP 发送时间: " << QDateTime::currentDateTime().toString();
        } else {
            updateMainResponse("错误：TCP 连接无效");
            isProcessingTopicQuery = false;
            isWaitingForTopicResponse = false;
        }
    } else if (mainWindow->getIsSerialConnected()) {
        QSerialPort *serialPort = mainWindow->getSerialPort();
        if (serialPort->isOpen()) {
            serialPort->write(command.toUtf8());
            serialPort->flush();
            updateMainResponse(desc + "命令已通过串口发送: " + command.trimmed());
            qDebug() << "sendTopicCommand: 串口发送时间: " << QDateTime::currentDateTime().toString();
        } else {
            updateMainResponse("错误：串口连接无效");
            isProcessingTopicQuery = false;
            isWaitingForTopicResponse = false;
        }
    } else {
        updateMainResponse("错误：未检测到可用的串口或TCP连接");
        isProcessingTopicQuery = false;
        isWaitingForTopicResponse = false;
    }
}

bool frmdeviceupdate::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->queryTopicTypeComboBox || watched == ui->queryTopicTypeComboBox->lineEdit()) {
        if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::LeftButton) {
                if (!ui->queryTopicTypeComboBox->isEnabled()) {
                    return true;
                }
                ui->queryTopicTypeComboBox->showPopup();
                return true;
            }
        }
    }
    return QWidget::eventFilter(watched, event);
}

void frmdeviceupdate::onWaitLogTimeout()
{
    if (!isWaitingForMqttConfig && !isWaitingForTopicResponse && !isWaitingForResponse) {
        waitLogTimer.stop();
        waitSeconds = 0;
        return;
    }
    waitSeconds++;
    updateMainResponse(QString("等待返回%1秒...").arg(waitSeconds));
}